package su.samlib.informer.utils.updaters.config;

import java.io.*;
import java.util.Properties;

public class ConfigFactory {
    private static final String CONFIG_PATH = "." + File.separator + "etc" + File.separator + "sinta";
    private static final String CONFIG_BASE_FILENAME = "cofig.xml";
    private static final String CONFIG_DATABASE_FILENAME = "dbconfig.xml";
    private static final Config CONFIG_BASE = new ConfigImpl(CONFIG_BASE_FILENAME);
    private static final Config CONFIG_DATABASE = new ConfigImpl(CONFIG_DATABASE_FILENAME);
    private static volatile ConfigFactory configFactory;

    private static class ConfigImpl extends Properties implements Config {
        private File configFile;
        private String CONFIG_FILENAME;
        private ConfigImpl(String configFileName) {
            CONFIG_FILENAME = configFileName;
            configFile = new File(CONFIG_PATH + File.separator+ CONFIG_FILENAME);
            try {
                load();
            } catch (IOException e) {
                System.out.println("Невозможно прочитать конфигурационный файл: " + CONFIG_FILENAME);
            }
        }

        @Override
        public synchronized void store() throws IOException {
                FileOutputStream fileOutputStream = new FileOutputStream(configFile);
                storeToXML(fileOutputStream, CONFIG_FILENAME);
        }

        @Override
        public synchronized void load() throws IOException {
                FileInputStream fileInputStream = new FileInputStream(configFile);
                loadFromXML(fileInputStream);
        }
    }

    private ConfigFactory() {}
    public static ConfigFactory newInstance() {
        synchronized (ConfigFactory.class) {
            if(configFactory == null) {
                configFactory = new ConfigFactory();
            }
            return configFactory;
        }
    };

    public Config getConfigBase() {
        synchronized (CONFIG_BASE) {
            return CONFIG_BASE;
        }
    }

    public Config getConfigDatabase() {
        synchronized (CONFIG_DATABASE) {
            return CONFIG_DATABASE;
        }
    }
}
